//
//  JSViewController48.swift
//  RXSwiftTest
//
//  Created by ZhangBo on 2019/6/19.
//  Copyright © 2019 ZhangBo. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import Alamofire
import RxAlamofire

class JSViewController48: BaseViewController {
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        test4()
    }

}

extension JSViewController48 {
    fileprivate func test1() {
        //指定下载路径（文件名不变）
        let destination: DownloadRequest.DownloadFileDestination = { _, response in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        //需要下载的文件
        let fileURL = URL(string: "http://www.hangge.com/blog/images/logo.png")!

        //开始下载
        download(URLRequest(url: fileURL), to: destination).subscribe(onNext: { element in
            print("开始下载。")
        }, onError: { error in
            print("下载失败! 失败原因：\(error)")
        }, onCompleted: {
            print("下载完毕!")
        }).disposed(by: disposeBag)
    }

    fileprivate func test2() {
        //指定下载路径和保存文件名
        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("file1/myLogo.png")
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        //需要下载的文件
        let fileURL = URL(string: "http://www.hangge.com/blog/images/logo.png")!

        //开始下载
        download(URLRequest(url: fileURL), to: destination).subscribe(onNext: { element in
            print("开始下载。")
        }, onError: { error in
            print("下载失败! 失败原因：\(error)")
        }, onCompleted: {
            print("下载完毕!")
        }).disposed(by: disposeBag)
    }

    fileprivate func test3() {
        //指定下载路径和保存文件名
        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("file1/myLogo.png")
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        //需要下载的文件
        let fileURL = URL(string: "https://up.enterdesk.com/edpic_source/d4/08/31/d408317fdb947b2df836b26c4227d922.jpg")!
        //开始下载
        download(URLRequest(url: fileURL), to: destination).subscribe(onNext: { element in
            print("开始下载。")
            element.downloadProgress(closure: { progress in
                print("当前进度: \(progress.fractionCompleted)")
                print("  已下载：\(progress.completedUnitCount / 1024)KB")
                print("  总大小：\(progress.totalUnitCount / 1024)KB")
            })
        }, onError: { error in
            print("下载失败! 失败原因：\(error)")
        }, onCompleted: {
            print("下载完毕!")
        }).disposed(by: disposeBag)
    }
}

extension JSViewController48 {
    fileprivate func test4() {

        //指定下载路径和保存文件名
        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("file1/myLogo.png")
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        //需要下载的文件
        let fileURL = URL(string: "https://up.enterdesk.com/edpic_source/d4/08/31/d408317fdb947b2df836b26c4227d922.jpg")!
        //开始下载
        self.view.addSubview(progressView)
        progressView.center = self.view.center

        download(URLRequest(url: fileURL), to: destination).map { request in
                //返回一个关于进度的可观察序列
                Observable<Float>.create { observer in
                    request.downloadProgress(closure: { (progress) in
                        observer.onNext(Float(progress.fractionCompleted))
                        if progress.isFinished {
                            observer.onCompleted()
                            self.progressView.removeFromSuperview()
                        }
                    })
                    return Disposables.create()
                }
            }
            .flatMap {
                $0
            }
            .bind(to: progressView.rx.progress) //将进度绑定UIProgressView上
            .disposed(by: disposeBag)
    }
}
